<template>
  <div class="page-container">
    <h2>用户管理</h2>
    <a-space style="margin-bottom: 20px">
      <a-button type="primary" @click="showUserModal = true">
        添加用户
      </a-button>
      <a-button type="primary" @click="batchImportUsers">
        批量导入连续用户
      </a-button>
    </a-space>
    <a-tabs v-model:activeKey="userTabKey" @change="handleTabChange">
      <a-tab-pane key="all" tab="全部用户"> </a-tab-pane>
      <a-tab-pane key="non-winners" tab="未中奖用户"> </a-tab-pane>
      <a-tab-pane key="winners" tab="已中奖用户"> </a-tab-pane>
    </a-tabs>
    <a-table :columns="columns" :data-source="userList" :pagination="false">
      <template #bodyCell="{ column, record }">
        <a-space v-if="column.key === 'action'">
          <a-button @click="editUser(record)">编辑</a-button>
          <a-button type="primary" danger @click="deleteUser(record.id)">
            删除
          </a-button>
        </a-space>
        <template v-else-if="column.key === 'prize_name'">
          {{ record.prize?.name || "-" }}
        </template>
      </template>
    </a-table>
    <a-pagination
      v-model:current="pagination.current"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      style="margin-top: 20px"
      @change="fetchData"
    />

    <!-- 用户模态框 -->
    <a-modal
      v-model:open="showUserModal"
      :title="userModalTitle"
      @ok="handleUserSubmit"
    >
      <a-form :model="userForm" layout="vertical">
        <a-form-item label="用户名">
          <a-input v-model:value="userForm.name" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="手机号码">
          <a-input
            v-model:value="userForm.phone"
            placeholder="请输入手机号码"
          />
        </a-form-item>
        <a-form-item label="部门">
          <a-input
            v-model:value="userForm.department"
            placeholder="请输入部门"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 批量导入模态框 -->
    <a-modal
      v-model:open="showBatchImportModal"
      title="批量导入用户"
      @ok="confirmBatchImport"
    >
      <a-form layout="vertical">
        <a-form-item label="导入数量">
          <a-input-number
            v-model:value="batchImportCount"
            placeholder="请输入导入数量"
            :min="1"
            :max="10000"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, createVNode, computed, watch } from "vue";
import { userApi } from "../../api";
import { Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";

const userTabKey = ref("all");

// 模态框状态
const showUserModal = ref(false);
const showBatchImportModal = ref(false);

// 模态框标题
const userModalTitle = ref("添加用户");

// 数据列表
const nonWinners = ref([]);
const winners = ref([]);
const userList = ref([]);

// 表单数据
const userForm = reactive({
  id: null,
  name: "",
  phone: "",
  department: "",
});

const batchImportCount = ref(100);

const columns = [
  { title: "ID", dataIndex: "id", key: "id" },
  { title: "用户名", dataIndex: "nickname", key: "nickname" },
  { title: "手机号码", dataIndex: "phone", key: "phone" },
  { title: "中奖奖品", dataIndex: "prize_name", key: "prize_name" },
  { title: "中奖轮次", dataIndex: "round", key: "round" },
  { title: "操作", key: "action" },
];

const userType = ref("all");

// 加载用户列表
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});
const fetchData = async () => {
  // 加载用户
  // 判断当前是否为已中奖用户
  let params = {
    page: pagination.current,
    pagesize: pagination.pageSize,
  };
  console.log(userType.value);
  switch (userType.value) {
    case "winners":
      params.is_winner = 1;
      break;
    case "non-winners":
      params.is_winner = 0;
      break;
    default:
      break;
  }
  const res = await userApi.list({
    ...params,
  });
  userList.value = res.data.list || [];
  pagination.total = res.data.total || 0;
};

// 创建/编辑用户
const editUser = (record) => {
  if (record) {
    userModalTitle.value = "编辑用户";
    Object.assign(userForm, record);
  } else {
    userModalTitle.value = "添加用户";
    Object.keys(userForm).forEach((key) => {
      userForm[key] = key === "id" ? null : "";
    });
  }
  showUserModal.value = true;
};

// 提交用户
const handleUserSubmit = async () => {
  try {
    if (userForm.id) {
      await userApi.update(userForm.id, userForm);
    } else {
      await userApi.create(userForm);
    }
    showUserModal.value = false;
    fetchData();
  } catch (error) {
    console.error("用户操作失败:", error);
  }
};

// 删除用户
const deleteUser = async (id) => {
  try {
    await userApi.delete(id);
    fetchData();
  } catch (error) {
    console.error("删除用户失败:", error);
  }
};

// 批量导入用户
const batchImportUsers = () => {
  showBatchImportModal.value = true;
};

// 确认批量导入
const confirmBatchImport = async () => {
  Modal.confirm({
    title: "确认批量导入",
    icon: createVNode(ExclamationCircleOutlined),
    content: "批量导入会清空现有数据，请在操作前再次确认",
    onOk: async () => {
      try {
        await userApi.batchImport(batchImportCount.value);
        showBatchImportModal.value = false;
        fetchData();
      } catch (error) {
        console.error("批量导入失败:", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
    class: "test",
  });
};

// 切换标签页时加载数据
const handleTabChange = (e) => {
  userType.value = e;
};
watch(userType, () => {
  pagination.current = 1;
  fetchData();
});

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.page-container {
  min-height: 600px;
}
</style>
